Bubble Sort Algorithm in Java
Here's a Java implementation of the Bubble Sort algorithm:
public class BubbleSortExample {
public static void main(String[] args) {
int[] array = {5, 3, 8, 6, 2};
System.out.println("Original Array:");
printArray(array);
bubbleSort(array);
System.out.println("Sorted Array:");
printArray(array);
}
// Bubble Sort Method
public static void bubbleSort(int[] arr) {
int n = arr.length;
boolean swapped;
// Outer loop for each pass
for (int i = 0; i < n - 1; i++) {
swapped = false;
// Inner loop for comparing adjacent elements
for (int j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
// Swap elements if they are in the wrong order
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
}
// If no swaps were made during a pass, the array is sorted
if (!swapped) {
break;
}
}
}
// Helper method to print the array
public static void printArray(int[] arr) {
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
}
}
Explanation
- Main Method:
- Initializes an array: {5, 3, 8, 6, 2}.
- Calls the bubbleSort method to sort the array.
- Prints the array before and after sorting using the printArray method.
- Bubble Sort Method:
- Loops through the array, comparing adjacent elements.
- Swaps elements if they are out of order.
- Tracks if any swaps were made using a boolean swapped.
- Breaks out of the loop early if the array is already sorted (optimization).
- Print Array Method:
- A simple utility to print the array elements.
Output
When you run the program, the output will be:
Original Array:
5 3 8 6 2
Sorted Array:
2 3 5 6 8
This implementation includes an optimization to stop the algorithm early if no swaps occur during a pass.
Let me know if you'd like further explanations on Bubble Sort Algorithm!